package com.liyuan.help_e.controller;

import com.alibaba.fastjson.JSONObject;
import com.liyuan.help_e.model.ResultJson;
import com.liyuan.help_e.model.User;
import com.liyuan.help_e.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class AuthenticationController {
    @Autowired
    UserService userService;
    @GetMapping("/authenticate_")
    public ResultJson authenticate_(){
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        if(username.equals("anonymousUser")){
            return new ResultJson(-2,"anonymousUser!",null);
        }
        return new ResultJson(200,"user",SecurityContextHolder.getContext().getAuthentication().getPrincipal());
    }
    @GetMapping("/login")
    public void login_Html(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/login.html").forward(request,response);
    }
    @PostMapping("/signin")
    public void signin(@RequestParam("username")String username,
                       @RequestParam("password")String password,
                       HttpServletRequest request,
                       HttpServletResponse response) throws ServletException, IOException {
        User user = userService.selectUserByUsername(username);
        if(user==null){
            userService.signin(username,password);
            response.sendRedirect("/signin.html?success");
        }else {
            response.sendRedirect("/signin.html?error");
        }
    }
//    @PostMapping("/signin")
//    public ResultJson signin(@RequestBody String jsonData){
//        JSONObject jsonObject = JSONObject.parseObject(jsonData);
//        String username = jsonObject.getString("username");
//        String password = jsonObject.getString("password");
//        User user = userService.selectUserByUsername(username);
//        if(user==null){
//            userService.signin(username,password);
//            return new ResultJson(200,"用户注册成功！",null);
//        }
//        return new ResultJson(-1,"用户名重复！",null);
//
//    }
}
